package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties WeChatProperties;

    @Autowired
    private UserMapper userMapper;





    /*
    * 微信登录
    * */
    @Override
    public User login(UserLoginDTO userLoginDTO) {

        // 1.调用微信服务器接口获取当前用户的openid
        String openid = getOpenid(userLoginDTO.getCode());

        // 2.判断openid是否为空，如果为空，则表示登录失败，抛出异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 3.判断是否为新用户？
        User user = userMapper.getByOpenid(openid);

        // 4.如果是新用户，自动完成注册
        if (user == null){
            //当前是一个新用户，自动完成注册
           user =User.builder()
                   .openid(openid)
                   .createTime(LocalDateTime.now())
                   .build();
           userMapper.insert(user);
        }

        // 5.返回用户对象信息
        log.info("微信登录成功，用户信息为：{}",user);
        return user;
    }



    /*
    * 调用微信服务器接口获取当前用户的openid
    * */
    private String getOpenid(String code){
        // 1.调用微信服务器接口获取当前用户的openid
        Map map = new HashMap();
        map.put("appid",WeChatProperties.getAppid());
        map.put("secret",WeChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String josn = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(josn);
        String openid = jsonObject.getString("openid");
        return openid;
    }



}
